package algotithm.leetcode.tree.test993;

import algotithm.leetcode.tree.TreeNode;
/**
 * @author 25068
 * @Date 2021/5/17 8:58
 * @Title 993. 二叉树的堂兄弟节点
 */


/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 * @author 25068
 */
public class Solution {
    int x;
    TreeNode xParent;
    int xDepth;
    boolean xFound;

    int y;
    TreeNode yParent;
    int yDepth;
    boolean yFound;
    public boolean isCousins(TreeNode root, int x, int y) {
        this.x = x;
        this.y = y;
        dfs(root,0,null);
        return xDepth == yDepth && xParent != yParent;
    }

    public void dfs(TreeNode node,int depth,TreeNode parent) {
        if (node == null) {
            return;
        }
        if (node.val == x) {
            xFound = true;
            xDepth = depth;
            xParent = parent;
        } else if (node.val == y) {
            yFound = true;
            yDepth = depth;
            yParent = parent;
        }
        if (xFound && yFound) {
            return;
        }
        dfs(node.left,depth + 1,node);
        if (xFound && yFound) {
            return;
        }
        dfs(node.right,depth + 1,node);


    }
}
